import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { getApiMallDetailSetting, getApiSystemMenu, getRestfulMallDetail, postV3PremiumList, postV3ZeusMallConfig } from "@/assets/api";
import { NavigationMenuRoute, NavigationMenuType } from "@/store/utils";

export const mallStore = defineStore('mall', {
    state: () => {
        return {
            mallId: 0,// 商场id
            companyId: 0,// 集团id
            companyManager: 1,// 当前账号状态 3：已禁用 4：已过期
            uniqueMember: 0,// 1：统一会员集团 否则 非统一会员集团
            mallEdition: 0,// 1：集团管理页，2：集团商场页
            system: 5,// 4：集团管理页；5：集团商场

            mallZeusConfig: {},// 宙斯商场配置
            mallDetail: {},// 商场详情
            mallDetailSetting: {},// 设置的商场详情
            parkConfig: {},// 停车配置

            navigationMenus: [],// 页面路由
            navigationMenusHas: {},// 头部导航栏字典下标 route.name:index

            companyName: '',// 集团名称
            mallName: '',// 商场名称
            layoutName: '',// 右上角 显示集团/商场 名称
            userName: '',// 右上角 用户名称

            isPaidMember: false,// 是否开通 付费会员商场
            paidMemberList: [],// 付费会员 卡信息
        }
    },
    getters: {
        // 统一会员集团
        isUniqueMember: (state: { uniqueMember: number }) => {
            return +state.uniqueMember === 1;
        },
        // 进入集团管理页
        isGroupManagementPage: (state: { mallEdition: number }) => {
            return +state.mallEdition === 1;
        },
        // 统一会员集团 集团页
        isUniqueMemberCompany: (state: { isUniqueMember: boolean, isGroupManagementPage: boolean }) => {
            return state.isUniqueMember && state.isGroupManagementPage;
        },
        // 统一会员集团 商场页
        isUniqueMemberMall: (state: { isUniqueMember: boolean, mallEdition: number }) => {
            return state.isUniqueMember && state.mallEdition === 2;
        },
        // 支持时长抵扣
        isSupportTimeDeduction: (state: ObjValueAny) => {
            return +state.parkConfig.support_time_deduction === 1;
        }
    },
    actions: {
        setCompanyName() {
            this.layoutName = this.companyName;
        },
        setMallName() {
            this.layoutName = this.mallName;
        },
        getResetApiStore(): Promise<void> {
            return new Promise(resolve => {
                const _promiseAll: ObjValueAny[] = [
                    this.getSystemMenuStore(),
                    this.getMallDetailStore(),
                    this.getMallDetailSettingStore(),
                    this.getZeusMallConfigStore(),
                    this.getPaidMemberStore(),
                ];
                Promise.all(_promiseAll).then(() => {
                    resolve()
                })
            })
        },
        // 页面路由
        getSystemMenuStore(): Promise<void> {
            return new Promise((resolve, reject) => {
                getApiSystemMenu().then((resp: { code?: number, data?: NavigationMenuType[], msg?: string }) => {
                    if (resp.code === 200) {
                        if (resp.data && resp.data.length) {
                            const hiddenRoutes = ['NotificationCenter'];
                            this.navigationMenus = resp.data.filter((row: NavigationMenuRoute) => !hiddenRoutes.includes(row.route));
                            let row: ObjValueNum = {};
                            let _length = this.navigationMenus.length;
                            for (let i = 0; i < _length; i++) {
                                getNavigationMenusHasTree(this.navigationMenus[i].children, row, i);
                            }
                            this.navigationMenusHas = row;
                        }
                        resolve();
                    } else {
                        ElMessage.error(`getApiSystemMenu：${resp.msg}`);
                        reject();
                    }
                });
            })
        },
        // 宙斯配置
        getZeusMallConfigStore(): Promise<void> {
            return new Promise(async (resolve, reject) => {
                postV3ZeusMallConfig().then((resp: ObjValueAny) => {
                    if (resp.code === 200) {
                        const { data } = resp;
                        data.defaultTemplate = true;
                        data.themeColor = '#deaf7d';
                        data.themeBgRgba = 'rgba(222,175,125,0.2)';
                        data.themeLinearBg = `linear-gradient(${data.themeColor},#f1d8b4)`;
                        if (data.miniapp && +data.miniapp.customize_template !== 1) {
                            data.defaultTemplate = false;
                            data.themeColor = '#ff4d5d';
                            data.themeBgRgba = 'rgba(232,84,94,0.2)';
                            data.themeLinearBg = 'linear-gradient(#f25c62,#ff9599)';
                        }
                        this.mallZeusConfig = data;
                        resolve();
                    } else {
                        ElMessage.error(`postV3ZeusMallConfig：${resp.msg}`);
                        reject();
                    }
                });
            })
        },
        // 商场 详情
        getMallDetailStore(): Promise<void> {
            return new Promise((resolve, reject) => {
                getRestfulMallDetail().then((resp: { code?: number, data?: object, msg?: string }) => {
                    if (resp.code === 200) {
                        this.mallDetail = resp?.data || {};
                        this.mallName = this.mallDetail.name || '';
                        resolve();
                    } else {
                        ElMessage.error(`getRestfulMallDetail：${resp.msg}`);
                        reject();
                    }
                });
            })
        },
        // 设置的商场 详情
        getMallDetailSettingStore(): Promise<void> {
            return new Promise(async (resolve, reject) => {
                getApiMallDetailSetting().then((resp: ObjValueAny) => {
                    if (resp.code === 200) {
                        this.mallDetailSetting = resp.data;
                        resolve();
                    } else {
                        ElMessage.error(`getApiMallDetailSetting：${resp.msg}`);
                        reject();
                    }
                })
            })
        },
        // 付费会员
        getPaidMemberStore(): Promise<void> {
            return new Promise(async (resolve, reject) => {
                postV3PremiumList().then((resp: ObjValueAny) => {
                    this.isPaidMember = false;
                    if (resp.code === 200) {
                        if (resp.data && resp.data.length) {
                            this.isPaidMember = true;
                            this.paidMemberList = resp.data;
                        }
                        resolve();
                    } else {
                        ElMessage.error(`postV3PremiumList：${resp.msg}`);
                        reject();
                    }
                });
            })
        },
    },
    persist: {
        enabled: true,// 开启持久化
        // 选择存储方式和内容
        strategies: [
            { storage: localStorage, paths: undefined }
        ]
    }
})

function getNavigationMenusHasTree(data: NavigationMenuType[], ele: ObjValueNum, index: number) {
    let _length = data.length;
    for (let i = 0; i < _length; i++) {
        let row: NavigationMenuType = data[i];
        if (row.route && !ele[row.route]) ele[row.route] = index;
        if (row.children && row.children.length) {
            getNavigationMenusHasTree(row.children as NavigationMenuType[], ele, index);
        }
    }
}